<?php

namespace app\admin\controller\oil;

use addons\sum\model\Config as ConfigModel;
use app\admin\library\Auth;
use app\common\controller\Backend;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use think\Db;
use think\db\exception\BindParamException;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;
use Exception;
use addons\sum\library\Export;
use think\response\Json;

/**
 * 门店
 *
 * @icon fa fa-circle-o
 */
class Store extends Backend
{

    /**
     * Store模型对象
     * @var \app\admin\model\oil\Store
     */
    protected $model = null;
    protected $fuel_model = null;
    /**
     * 是否开启数据限制
     * 支持auth/personal
     * 表示按权限判断/仅限个人
     * 默认为禁用,若启用请务必保证表中存在admin_id字段
     */
//    protected $dataLimit = 'auth';
    /**
     * 数据限制字段
     */
//    protected $dataLimitField = 'admin_id';

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\oil\Store;
        $this->fuel_model = new \app\admin\model\oil\Fuel;

        // 获取 amap key
        $config = \addons\sum\model\Config::get(['name' => 'services']);
        $config = ($config && $config->value) ? json_decode($config->value, true) : [];

        $amapConfig = $config['amap'] ?? [];
        $hasAmap = ($amapConfig && $amapConfig['appkey']) ? true : false;
        $this->assignconfig("hasAmap", $hasAmap);
        $this->assign("amap", $amapConfig);
    }
    

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    /**
     * 批量改价
     * @param $ids
     */
    public function edit_price()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post();
            if ($params) {
                $params = json_decode($params['data'], true);
                if($params['pcd_level']==1){
                    $store_map['province_id']=$params['province_id'];
                }
                if($params['pcd_level']==2){
                    $store_map['city_id']=$params['city_id'];
                }
                if($params['pcd_level']==3){
                    $store_map['area_id']=$params['area_id'];
                }
                $store_ids=$this->model->where($store_map)->column('id');
                if(!$store_ids){
                    $this->error('该区域没有找到油站记录');
                }
                $result = false;
                $data[$params['price_type']]=$params['price'];

                Db::startTrans();
                try {
                    $this->fuel_model->whereIn('store_id',$store_ids)->where('type',$params['fuel_type'])->update($data);
                    $result = true;
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success('操作成功');
                } else {
                    $this->error(__('操作错误'));
                }
            }
            $this->error(__('参数错误'));
        }
        $oil_config=json_decode(ConfigModel::where('name','oil')->value('value'),true);
        $this->oil_config=$oil_config;
        $this->assignconfig("fuelTypeList", $oil_config['fuel_type']);

        return $this->view->fetch();
    }


  /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax())
        {
            $search = $this->request->get('search');
            list($where, $sort, $order, $offset, $limit) = $this->buildparams('name');
            $total = $this->model
                    ->where($where)
//                    ->whereOr('name', 'LIKE', "%$search%")
                    ->order($sort, $order)
                    ->count();

            $list = $this->model
//                    ->with(['admin'])
                    ->with(['printer'])
                    ->where($where)
//                    ->whereOr('name', 'LIKE', "%$search%")
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return $this->success('油站列表', null, $result);
        }
        return $this->view->fetch();
    }


    public function all() {
        if ($this->request->isAjax()) {
            $search = $this->request->get('search');

            $list = $this->model
                    ->where('name', 'LIKE', "%$search%")
                    ->order('id', 'desc')
                    ->select();

            return $this->success('操作成功', null, $list);
        }
    }


    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post();
            if ($params) {
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                $params = json_decode($params['data'], true);
                Db::startTrans();
                try {
                    $result = $this->model->allowField(true)->save($params);
//                    $this->setStoreManager($this->model->id, $params['user_ids']);
                    if (!$result) {
                        $this->error($this->model->getError());
                    }
                    Db::commit();

                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success("添加成功");
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }


   /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post();
            if ($params) {
                $params = json_decode($params['data'], true);
                $result = false;
                Db::startTrans();
                try {
                    $row->allowField(true)->save($params);
//                    $this->setStoreManager($row->id, $params['user_ids']);
                    $row->save();
                    $result = true;
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        
        $this->assignconfig("row", $row);
        return $this->view->fetch();
    }

    public function setStatus($ids, $status) {
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();

            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    $v->status = $status;
                    $count += $v->save();
                }
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were updated'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

    public function select()
    {
        //当前是否为关联查询
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax())
        {
            $searchWhere = $this->request->get('searchWhere');
//            print_r($searchWhere);
//            exit();
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                        ->where($where)
                        ->where(function($query) use($searchWhere) {
                        return $query
                        ->whereOr('id', 'LIKE', "%$searchWhere%")
                        ->whereOr('name', 'LIKE', "%$searchWhere%")
                        ->whereOr('address', 'LIKE', "%$searchWhere%")
                        ->whereOr('province_name', 'LIKE', "%$searchWhere%")
                        ->whereOr('city_name', 'LIKE', "%$searchWhere%")
                        ->whereOr('area_name', 'LIKE', "%$searchWhere%");
                    })
                    ->order($sort, $order)
                    ->count();

            $list = $this->model
                       ->where($where)
                       ->where(function($query) use($searchWhere) {
                        return $query
                        ->whereOr('id', 'LIKE', "%$searchWhere%")
                       ->whereOr('name', 'LIKE', "%$searchWhere%")
                       ->whereOr('address', 'LIKE', "%$searchWhere%")
                       ->whereOr('province_name', 'LIKE', "%$searchWhere%")
                       ->whereOr('city_name', 'LIKE', "%$searchWhere%")
                       ->whereOr('area_name', 'LIKE', "%$searchWhere%");
                    })
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return $this->success('油站列表', null, $result);
        }
    }

    /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function select2()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model
            ->where($where)
            ->order($sort, $order)
            ->paginate($limit);
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }

    // 油站导出
    public function store_export()
    {
        list($where, $sort, $order, $offset, $limit) = $this->buildparams();

        $oil_config=json_decode(ConfigModel::where('name','oil')->value('value'),true);
        $type_list=$oil_config['fuel_type'];
        $expCellName = [
            'id' => 'ID',
            'name' => '油站名称',
            'realname' => '联系人',
            'phone' => '联系电话',
            'province_name' => '省',
            'city_name' => '市',
            'area_name' => '区',
            'province_id' => '省ID',
            'city_id' => '市ID',
            'area_id' => '区ID',
            'address' => '详细地址',
            'latitude' => '纬度',
            'longitude' => '经度',
            'openhours' => '营业时间',
//            'discount_max' => '最大优惠',
            'need_count' => '激活所需',
        ];
//        foreach ($type_list as $tlv){
//            $expCellName['fuel_price_'.$tlv['slug']]=$tlv['name'].'挂机价';
//            $expCellName['fuel_original_price_'.$tlv['slug']]=$tlv['name'].'指导价';
//            $expCellName['fuel_guns_'.$tlv['slug']]=$tlv['name'].'油枪号';
//        }

        $export = new Export();
        $spreadsheet = null;
        $sheet = null;

        $total = $this->model
            ->where($where)
            ->order($sort, $order)
            ->count();

        $current_total = 0;     // 当前已循环条数
        $page_size = 2000;
        $total_page = intval(ceil($total / $page_size));
        if ($total == 0) {
            $this->error('导出数据为空');
        }
        for ($i = 0; $i < $total_page; $i++) {
            $page = $i + 1;
            $is_last_page = ($page == $total_page) ? true : false;

            $list = $this->model
                ->field('*')
                ->where($where)
                ->order($sort, $order)
                ->limit(($i * $page_size), $page_size)
                ->select();
            $list = collection($list)->toArray();
            $current_total += count($list);     // 当前循环总条数
            $export->exportExcel('油站列表-' . date('Y-m-d H:i:s'), $expCellName, $list, $spreadsheet, $sheet, [
                'page' => $page,
                'current_total' => $current_total,
                'is_last_page' => $is_last_page
            ]);
        }
    }

    // 油品导出-这个是按油站
    public function fuel_export()
    {
        list($where, $sort, $order, $offset, $limit) = $this->buildparams();

        $oil_config=json_decode(ConfigModel::where('name','oil')->value('value'),true);
        $type_list=$oil_config['fuel_type'];
        $expCellName = [
            'id' => 'ID',
            'store_id' => '油站ID',
            'store_name' => '油站名称',
            'name' => '油品名称',
            'type' => '油品标识',
            'guns' => '油枪号',
            'price' => '特价平台价',
            'chengben_price' => '成本价',
            'tjchengben_price' => '特价成本价',
            'guaji_price' => '挂机价',
            'original_price' => '指导价',
//            'discount_max' => '每升最大优惠',
        ];
        $export = new Export();
        $spreadsheet = null;
        $sheet = null;
        $total = $this->model
            ->where($where)
            ->order($sort, $order)
            ->count();

        $current_total = 0;     // 当前已循环条数
        $page_size = 2000;
        $total_page = intval(ceil($total / $page_size));
        if ($total == 0) {
            $this->error('导出数据为空');
        }
        for ($i = 0; $i < $total_page; $i++) {
            $page = $i + 1;
            $is_last_page = ($page == $total_page) ? true : false;

            $list = $this->model
                ->with('fuel')
                ->where($where)
                ->order($sort, $order)
                ->limit(($i * $page_size), $page_size)
                ->select();
            $list = collection($list)->toArray();
            $newList = [];
            foreach ($list as $key => $vo) {
                $data = [
                    'store_id' => $vo['id'],
                    'store_name' => $vo['name'],
                ];
                foreach ($vo['fuel'] as $fuel){
                    $data['fuel_id_'.$fuel['type']]=$fuel['id'];
                    $data['fuel_name_'.$fuel['type']]=$fuel['name'];
                    $data['fuel_price_'.$fuel['type']]=$fuel['price'];
                    $data['fuel_chengben_price_'.$fuel['type']]=$fuel['chengben_price'];
                    $data['fuel_tjchengben_price_'.$fuel['type']]=$fuel['tjchengben_price'];
                    $data['fuel_guaji_price_'.$fuel['type']]=$fuel['guaji_price'];
                    $data['fuel_original_price_'.$fuel['type']]=$fuel['original_price'];
//                    $data['fuel_discount_max_'.$fuel['type']]=$fuel['discount_max'];
                    $data['fuel_guns_'.$fuel['type']]=$fuel['guns'];
                }
                foreach ($type_list as $tlv){
                    $item['id']=$data['fuel_id_'.$tlv['slug']]??'';
                    $item['name']=$data['fuel_name_'.$tlv['slug']]??'';
                    $item['type']=$tlv['slug'];
                    $item['guns']=$data['fuel_guns_'.$tlv['slug']]??'';
                    $item['price']=$data['fuel_price_'.$tlv['slug']]??'';
                    $item['chengben_price']=$data['fuel_chengben_price_'.$tlv['slug']]??'';
                    $item['tjchengben_price']=$data['fuel_tjchengben_price_'.$tlv['slug']]??'';
                    $item['guaji_price']=$data['fuel_guaji_price_'.$tlv['slug']]??'';
                    $item['original_price']=$data['fuel_original_price_'.$tlv['slug']]??'';
//                    $item['discount_max']=$data['fuel_discount_max_'.$tlv['slug']]??'';
                    $newList[] = array_merge($data, $item);
                }

            }
            $current_total += count($newList);     // 当前循环总条数
            $export->exportExcel('油品列表-' . date('Y-m-d H:i:s'), $expCellName, $newList, $spreadsheet, $sheet, [
                'page' => $page,
                'page_size' => $page_size,      // 如果传了 current_total 则 page_size 就不用了
                'current_total' => $current_total,      // page_size 是 order 的，但是 newList 其实是 order_item 的
                'is_last_page' => $is_last_page
            ]);
        }
    }

    // 油品导出-这个是按油品
    public function fuel_export_byfuel()
    {
        $oil_config=json_decode(ConfigModel::where('name','oil')->value('value'),true);
        $type_list=$oil_config['fuel_type'];
        $expCellName = [
            'id' => 'ID',
            'store_id' => '油站Id',
            'store_name' => '油站名称',
            'name' => '油品名称',
            'type' => '油品标识',
            'guns' => '油枪号',
            'price' => '挂机价',
            'original_price' => '指导价'
        ];
        $export = new Export();
        $spreadsheet = null;
        $sheet = null;
        $where=[];
        $total = $this->fuel_model
            ->where($where)
            ->order('store_id', 'DESC')
            ->count();

        $current_total = 0;     // 当前已循环条数
        $page_size = 2000;
        $total_page = intval(ceil($total / $page_size));
        if ($total == 0) {
            $this->error('导出数据为空');
        }
        for ($i = 0; $i < $total_page; $i++) {
            $page = $i + 1;
            $is_last_page = ($page == $total_page) ? true : false;

            $list = $this->fuel_model
                ->with('store')
                ->where($where)
                ->order('store_id','DESC')
                ->limit(($i * $page_size), $page_size)
                ->select();
            $list = collection($list)->toArray();
            foreach ($list as $lk=>$lv){
                $list[$lk]['store_name']=$lv['store']['name']??'';
            }
            $current_total += count($list);     // 当前循环总条数
            $export->exportExcel('油品列表-' . date('Y-m-d H:i:s'), $expCellName, $list, $spreadsheet, $sheet, [
                'page' => $page,
                'current_total' => $current_total,
                'is_last_page' => $is_last_page
            ]);
        }
    }


    // 数据导入

    /**
     * 油站导入
     *
     * @return void
     * @throws PDOException
     * @throws BindParamException
     */
    public function storeImport()
    {
        $file = $this->request->request('url');
        if (!$file) {
            $this->error(__('Parameter %s can not be empty', 'file'));
        }
        $filePath = ROOT_PATH . DS . 'public' . DS . $file;
        if (!is_file($filePath)) {
            $this->error(__('No results were found'));
        }
        //实例化reader
        $ext = pathinfo($filePath, PATHINFO_EXTENSION);
        if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
            $this->error(__('Unknown data format'));
        }
        if ($ext === 'csv') {
            $file = fopen($filePath, 'r');
            $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
            $fp = fopen($filePath, 'w');
            $n = 0;
            while ($line = fgets($file)) {
                $line = rtrim($line, "\n\r\0");
                $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
                if ($encoding !== 'utf-8') {
                    $line = mb_convert_encoding($line, 'utf-8', $encoding);
                }
                if ($n == 0 || preg_match('/^".*"$/', $line)) {
                    fwrite($fp, $line . "\n");
                } else {
                    fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
                }
                $n++;
            }
            fclose($file) || fclose($fp);

            $reader = new Csv();
        } elseif ($ext === 'xls') {
            $reader = new Xls();
        } else {
            $reader = new Xlsx();
        }

        //导入文件首行类型,默认是注释,如果需要使用字段名称请使用name
        $importHeadType = isset($this->importHeadType) ? $this->importHeadType : 'comment';

        $table = $this->model->getQuery()->getTable();
        $database = \think\Config::get('database.database');
        $fieldArr = [];
        $list = db()->query("SELECT COLUMN_NAME,COLUMN_COMMENT FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ? AND TABLE_SCHEMA = ?", [$table, $database]);
        foreach ($list as $k => $v) {
            if ($importHeadType == 'comment') {
                $v['COLUMN_COMMENT'] = explode(':', $v['COLUMN_COMMENT'])[0]; //字段备注有:时截取
                $fieldArr[$v['COLUMN_COMMENT']] = $v['COLUMN_NAME'];
            } else {
                $fieldArr[$v['COLUMN_NAME']] = $v['COLUMN_NAME'];
            }
        }
//        print_r($list);
//        exit();
        //加载文件
        $insert = [];
        try {
            if (!$PHPExcel = $reader->load($filePath)) {
                $this->error(__('Unknown data format'));
            }
            $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
            $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
            $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
            $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
            $fields = [];
            for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $fields[] = $val;
                }
            }

            for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
                $values = [];
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $values[] = is_null($val) ? '' : $val;
                }
                $row = [];
                $temp = array_combine($fields, $values);
                foreach ($temp as $k => $v) {
                    if (isset($fieldArr[$k]) && $k !== '') {
                        $row[$fieldArr[$k]] = $v;
                    }
                }
                if ($row) {
                    $insert[] = $row;
                }
            }
        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }
        if (!$insert) {
            $this->error(__('No rows were updated'));
        }
//        print_r($insert);
//        exit();
        try {
            //是否包含admin_id字段
            $has_admin_id = false;
            foreach ($fieldArr as $name => $key) {
                if ($key == 'admin_id') {
                    $has_admin_id = true;
                    break;
                }
            }
            if ($has_admin_id) {
                $auth = Auth::instance();
                foreach ($insert as &$val) {
                    if (empty($val['admin_id'])) {
                        $val['admin_id'] = $auth->isLogin() ? $auth->id : 0;
                    }
                }
            }
            $this->model->saveAll($insert);
        } catch (PDOException $exception) {
            $msg = $exception->getMessage();
            if (preg_match("/.+Integrity constraint violation: 1062 Duplicate entry '(.+)' for key '(.+)'/is", $msg, $matches)) {
                $msg = "导入失败，包含【{$matches[1]}】的记录已存在";
            };
            $this->error($msg);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }

        $this->success();
    }

    /**
     * 油站导入
     *
     * @return void
     * @throws PDOException
     * @throws BindParamException
     */
    public function fuelImport()
    {
        $file = $this->request->request('url');
        if (!$file) {
            $this->error(__('Parameter %s can not be empty', 'file'));
        }
        $filePath = ROOT_PATH . DS . 'public' . DS . $file;
        if (!is_file($filePath)) {
            $this->error(__('No results were found'));
        }
        //实例化reader
        $ext = pathinfo($filePath, PATHINFO_EXTENSION);
        if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
            $this->error(__('Unknown data format'));
        }
        if ($ext === 'csv') {
            $file = fopen($filePath, 'r');
            $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
            $fp = fopen($filePath, 'w');
            $n = 0;
            while ($line = fgets($file)) {
                $line = rtrim($line, "\n\r\0");
                $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
                if ($encoding !== 'utf-8') {
                    $line = mb_convert_encoding($line, 'utf-8', $encoding);
                }
                if ($n == 0 || preg_match('/^".*"$/', $line)) {
                    fwrite($fp, $line . "\n");
                } else {
                    fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
                }
                $n++;
            }
            fclose($file) || fclose($fp);

            $reader = new Csv();
        } elseif ($ext === 'xls') {
            $reader = new Xls();
        } else {
            $reader = new Xlsx();
        }

        //导入文件首行类型,默认是注释,如果需要使用字段名称请使用name
        $importHeadType = isset($this->importHeadType) ? $this->importHeadType : 'comment';

        $table = $this->fuel_model->getQuery()->getTable();
        $database = \think\Config::get('database.database');
        $fieldArr = [];
        $list = db()->query("SELECT COLUMN_NAME,COLUMN_COMMENT FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ? AND TABLE_SCHEMA = ?", [$table, $database]);
        foreach ($list as $k => $v) {
            if ($importHeadType == 'comment') {
                $v['COLUMN_COMMENT'] = explode(':', $v['COLUMN_COMMENT'])[0]; //字段备注有:时截取
                $fieldArr[$v['COLUMN_COMMENT']] = $v['COLUMN_NAME'];
            } else {
                $fieldArr[$v['COLUMN_NAME']] = $v['COLUMN_NAME'];
            }
        }
//        print_r($list);
//        exit();
        //加载文件
        $insert = [];
        try {
            if (!$PHPExcel = $reader->load($filePath)) {
                $this->error(__('Unknown data format'));
            }
            $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
            $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
            $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
            $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
            $fields = [];
            for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $fields[] = $val;
                }
            }

            for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
                $values = [];
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $values[] = is_null($val) ? '' : $val;
                }
                $row = [];
                $temp = array_combine($fields, $values);
                foreach ($temp as $k => $v) {
                    if (isset($fieldArr[$k]) && $k !== '') {
                        $row[$fieldArr[$k]] = $v;
                    }
                }
                if ($row) {
                    $insert[] = $row;
                }
            }
        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }
        if (!$insert) {
            $this->error(__('No rows were updated'));
        }
//        print_r($insert);
//        exit();
        try {
            //是否包含admin_id字段
            $has_admin_id = false;
            foreach ($fieldArr as $name => $key) {
                if ($key == 'admin_id') {
                    $has_admin_id = true;
                    break;
                }
            }
            if ($has_admin_id) {
                $auth = Auth::instance();
                foreach ($insert as &$val) {
                    if (empty($val['admin_id'])) {
                        $val['admin_id'] = $auth->isLogin() ? $auth->id : 0;
                    }
                }
            }
            $this->fuel_model->saveAll($insert);
        } catch (PDOException $exception) {
            $msg = $exception->getMessage();
            if (preg_match("/.+Integrity constraint violation: 1062 Duplicate entry '(.+)' for key '(.+)'/is", $msg, $matches)) {
                $msg = "导入失败，包含【{$matches[1]}】的记录已存在";
            };
            $this->error($msg);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }

        $this->success();
    }
    private function setStoreManager($store_id, $user_ids)
    {
        $user_ids = explode(',', $user_ids);
        $existUserIds = Db::name('oil_user_store')
            ->where('store_id', $store_id)
            ->column('user_id');
        $newUserIds = array_diff($user_ids, $existUserIds);

        $deleteUserIds = array_diff($existUserIds, $user_ids);

        $newData = [];
        foreach($newUserIds as $id) {
            $newData[] = [
                'user_id' => $id,
                'store_id' => $store_id
            ];
        }
        if (!empty($newData)) {
            Db::name('oil_user_store')->insertAll($newData);
        }

        if (!empty($deleteUserIds)) {
            Db::name('oil_user_store')->where('user_id', 'in', $deleteUserIds)
                ->where('store_id', $store_id)->delete();
        }
    }

}
